package cn.com.huzo.service.master.impl;

import cn.com.huzo.common.util.ApplicationConfiguration;
import huzofw.common.web.exception.HuzoDataAccessException;
import cn.com.huzo.model.entities.master.DepartmentEntity;
import huzofw.model.entities.viewmodel.TreeNode;
import cn.com.huzo.repository.master.DepartmentRepository;
import huzofw.service.impl.GenericManagerImpl;
import cn.com.huzo.service.master.DepartmentManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 部门管理服务对象类实现。
 *
 * @author 吴旭
 */
@Service("DepartmentManager")
public class DepartmentManagerImpl extends GenericManagerImpl<DepartmentEntity, Long>
        implements DepartmentManager {

    private final String rootNodeText = (String) ApplicationConfiguration.getProperty("CompanyName");

    @Resource(name = "DepartmentRepository")
    private DepartmentRepository _dao;

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public DepartmentEntity fetchByKey(Long key) throws Exception {
        return _dao.fetchByKey(key);
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public List<TreeNode> fetchTreeNodeByParentKey(Long parentKey, Integer isPopupWnd, Boolean IsAdiministrator) throws Exception {
        List<TreeNode> _listTree = new ArrayList();

        List<DepartmentEntity> _listDept = _dao.fetchTreeNodeByParentKey(rootNodeText, parentKey, IsAdiministrator);

        // 重新构建jsTree用json数据
        _listDept.stream().forEach((DepartmentEntity item) -> {
            TreeNode _node = new TreeNode();
            _node.setId(item.getDepartmentId());
            _node.setText(item.getDepartmentName());
            _node.setChildren((item.getNumChildren() > 0));
            if (parentKey == -1) {
                _node.setType("root");
            } else {
                switch (item.getDepartmentId().intValue()) {
                    case -10:
                        _node.setType("trash");
                        break;
                    default:
                        _node.setType("leaf");
                        break;
                }
            }
            // 设置属性
            Map<String, String> _li_attr = new HashMap();
            _li_attr.put("nodeType", item.getNodeType());
            if (item.getParentName().equals("")) {
                _li_attr.put("fullName", item.getDepartmentName());
            } else {
                _li_attr.put("fullName", item.getParentName() + " → " + item.getDepartmentName());
            }
            _node.setLi_attr(_li_attr);

            // 如果是弹出选择窗口，那么不显示《回收站》
            if ((isPopupWnd == 1) && (item.getDepartmentId().intValue() != -10)) {
                _listTree.add(_node);
            } else if (isPopupWnd == 0) {
                _listTree.add(_node);
            }
        });

        return _listTree;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Long insert(DepartmentEntity instance) throws Exception {
        Long key = _dao.insert(instance);
        // 审计日志
        if (key > 0) {
            writeAuditLog(instance.getUpdatedBy(), "基础信息→部门信息", "部门：" + instance.getDepartmentName(), "增加");
        }

        return key;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Integer update(DepartmentEntity instance) throws Exception {
        Integer rowsAffected = _dao.update(instance);
        // 审计日志
        if (rowsAffected > 0) {
            writeAuditLog(instance.getUpdatedBy(), "基础信息→部门信息", "部门：" + instance.getDepartmentName(), "更新");
        }

        return rowsAffected;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Integer changeParentCatalogue(Map<String, Object> nodeParams) throws Exception {
        return _dao.changeParentCatalogue(nodeParams);
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Integer delete(DepartmentEntity instance) throws Exception {
        if (_dao.isNullNode(instance.getDepartmentId()) > 0) {
            throw new HuzoDataAccessException("为确保安全，请先删除子节点或关联信息。");
        }
        DepartmentEntity entity = _dao.fetchByKey(instance.getDepartmentId());
        // 删除
        Integer rowsAffected = _dao.delete(instance.getDepartmentId());
        // 审计日志
        if (rowsAffected > 0) {
            writeAuditLog(instance.getDeletedBy(), "基础信息→部门信息", "部门：" + entity.getDepartmentName(), "删除");
        }

        return rowsAffected;
    }
}
